package handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Calendar;

/**
 * @author zy.jordan
 */
public class FirstClientHandler extends ChannelInboundHandlerAdapter {
  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    System.out.println(Calendar.getInstance() + ": 客户端写出数据");
    // 1、写数据
    ByteBuf buf = getByteBuf(ctx);

    // 2、写数据
    ctx.channel().writeAndFlush(buf);
  }

  private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
    // 1、获取二进制抽象 ByteBuf
    ByteBuf buf = ctx.alloc().buffer(1024);

    // 2、准备数据，指定字符集
    byte[] bytes = "你好，Jordan".getBytes();

    // 3、填充数据到 ByteBuf
    buf.writeBytes(bytes);

    return buf;
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf buf = (ByteBuf) msg;
    System.out.println(Calendar.getInstance() + ": 客户端读到数据 -> " + buf.toString(Charset.defaultCharset()));
  }
}
